<template>
	<view class="content">
    <view class="searchcomp">
      <view  @click="gosearchcomp" class="destplace">选择目的地</view>
    </view>
     <view class="maparea">
       <map id="indexmap" :longitude="marks[0].longitude" :latitude="marks[0].latitude"  style="width:100vw;height:78vh" scale="18" :markers="marks" :polyline="polyline" show-location>
        </map>
        <img src="../../static/myas.svg" alt="" class="myas" @click="myas">
     </view>
     <!-- v-show="destdistance" -->
      <view class="footer" >
        <text class="distance">当前距离目的地：{{destdistance}} </text>
        <button class="starttaxi" @click="starttaxi">开始打车</button>
      </view>
    </view> 
	</view>
</template>

<script>
  import ZqSearch from '../../components/search/ZqSearch.vue'
  import mtokm from '../../utils/mtokm.js'
  import {baseUrl1} from '../../common/config.js'
 const QQMapWX = require('../../libs/txmapv2');
  // 实例化API核心类
const qqmapsdk = new QQMapWX({
    key: 'OMYBZ-YFSK2-DD5UX-CZS76-FM6Z2-KYFTF' 
  });
	export default {
		data() {
			return {
          destdistance:0,
          nearcar:[],
          jhnearcar:[],
          polyline:null,
          marks:[
               {
                 id:0,
                 iconPath:"/static/locaton.svg",
                 longitude:"113.922775",
                 latitude:"22.773672",
                 callout:{
                   content:"我的位置",
                   color:'#ff0000',
                   padding:6,
                    display:"ALWAYS",
                 },
                 width:30,
                 height:30
               }
           ]
			}
		},
    components:{
      ZqSearch,
    },
    methods:{
      // 获取附近司机列表（java）
      getnearlistjh(distance=500){
        uni.request({
          url:baseUrl1+'/search',
          method:"GET",
          data:{
            lat:this.marks[0].latitude,
            lon:this.marks[0].longitude,
            distance:distance
          },
          success: (res) => {
            // 存储附近司机数据到 vuex  
            console.log(111,this.$store)
            this.$store.commit("changejgnearcar",res.data.data)
            this.jhnearcar = res.data.data
            for(let i = 0;i< res.data.data.length;i++){
              this.marks.push({
                 id:res.data.data[i].carId,
                 iconPath:res.data.data[i].carImg,
                 longitude:res.data.data[i].location.lon,
                 latitude:res.data.data[i].location.lat,
                 display:"ALWAYS",
                 width:30,
                 height:30
               })
            }
          }
        })
      },
      // 跳转到目的地搜索页面
      gosearchcomp(){
        uni.navigateTo({
          url:'../../components/search/ZqSearch'
        })
      },
      // 获取目的地到当前的距离
      getdistaance(value){
          var _this = this;
          // 调用距离计算接口
          qqmapsdk.calculateDistance({
            mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
            to: value, //终点坐标
            success: function(res) {//成功后的回调
            var res = res.result;
            _this.destdistance=mtokm(res.elements[0].distance)
          },
            fail: function(error) {
              console.error(error);
            },
            complete: function(res) {
          }
      })
      },
      // 线路规划
      routeplanning(value){
            const _this = this;
            //调用距离计算接口
            qqmapsdk.direction({
              mode: 'driving',
              from: `${_this.marks[0].latitude},${_this.marks[0].longitude}`,
              to: value, 
              success: function (res) {
                var ret = res;
                var coors = ret.result.routes[0].polyline, pl = [];
                //坐标解压（返回的点串坐标，通过前向差分进行压缩）
                var kr = 1000000;
                for (var i = 2; i < coors.length; i++) {
                  coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
                }
                //将解压后的坐标放入点串数组pl中
                for (var i = 0; i < coors.length; i += 2) {
                  pl.push({ latitude: coors[i], longitude: coors[i + 1] })
                }
                //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
                _this.polyline = [{
                    points: pl,
                    arrowLine:true,
                    color: '#FF0000DD',
                    width: 4
                  }]
                  // 动态追加目标地址mask
                  _this.marks.push({
                       id:1,
                       iconPath:"/static/dest.svg",
                       longitude:pl[pl.length-1].longitude,
                       latitude:pl[pl.length-1].latitude,
                       callout:{
                         content:"目标位置",
                          display:"ALWAYS",
                          color:'#ff0000',
                          padding:6,
                       },
                       display:"ALWAYS",
                       width:30,
                       height:30
                  })
              },
            
            });
      },
      // 或取附近司机列表 (node 模拟)
      getnearlist(){
        uni.request({
          url:"http://localhost:3000/nearcar",
          success: (res)=> {
            // console.log(this)
            this.nearcar = res.data.data
            for(let i = 0;i< res.data.data.length;i++){
              this.marks.push({
                 id:res.data.data[i].id,
                 iconPath:res.data.data[i].carimg,
                 longitude:res.data.data[i].longitude,
                 latitude:res.data.data[i].latitude,
                 callout:{
                   content:`司机：${res.data.data[i].drivername}`,
                    display:"ALWAYS",
                 },
                 display:"ALWAYS",
                 width:40,
                 height:40
               })
            }
          }
        })
      },
      // 点击瞄准定位到原地址
      myas(){
        uni.createSelectorQuery().select("#indexmap").context(res=>{
          console.log(res)
          res.context.moveToLocation()
        }).exec()
      },
      // 开始打车
      starttaxi(){
        // 把附近车辆信息存储到vuex
        uni.navigateTo({
          url:"/pages/taxi/taxi",
          success: () => {
            this.$store.commit("changenearcar",this.nearcar)
          }
        })
      }
    },
    
		onLoad() {
        uni.getLocation({
          type: 'gcj02',
          success:(res)=>{
            this.marks[0].latitude = res.latitude
            this.marks[0].longitude = res.longitude
            console.log(res.latitude,res.longitude)
            this.getnearlistjh(5000)
          }
        })
       // 可以被注释
        // this.getnearlist()
      },
      
    onShow(){
     if(this.$store.state.destareainfo.longitude){
       const {longitude,latitude} = this.$store.state.destareainfo
       this.getdistaance(`${latitude},${longitude}`)
       this.routeplanning(`${latitude},${longitude}`)
       }
     }
	}
</script>

<style scoped>
  .searchcomp{
  }
  .map_container{ 
      height: 300px; 
      width: 100%; 
  } 
  .maparea{
    position:relative ;
  }
  .myas{
    width: 40px;
    height: 40px;
    position: absolute;
    right: 10px;
    bottom: 20px;
  }
  .map { 
      height: 100%; 
      width: 100%; 
  } 
  .Taxi{
    margin: 0 auto;
    line-height: 30px;
    padding: 6px 40px;
    border-radius: 23px;
    text-align: center;
    color:red;
    font-size: 24px;
    font-weight: 700;
    background-color: aquamarine;
  }
  .destplace{
    background-color: #dddd;
    padding: 10px 20px;
    margin: 10px;
    border-radius: 10px; 
  },
  .footer{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
  }
  .starttaxi{
    background-color: #FF4500;
    padding: 6px 10px;
    line-height: 30px;
    margin: 0;
    color:#fff;
  }
</style>
